package com.tanger.common.enums;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
* @ClassName: EnumTypeHandler 
* @Description: 使用方式如下:
 * <resultMap>
 *     <result column="type" property="type" javaType="com.brt.base.common.enums.EnumIsAble" typeHandler="com.brt.base.common.utils.EnumTypeHandler" />
 * </resultMap>
* @author Hchenbin
* @date 2022/7/21 16:34:54
*  
*/
public class EnumTypeHandler extends BaseTypeHandler<BasicEnum> {

    private Class<BasicEnum> type;

    /**
     * 构造函数<br>
     */
    public EnumTypeHandler(Class<BasicEnum> type) {
        this.type = type;
    }

    @Override
    public BasicEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int value = rs.getInt(columnName);
        if (rs.wasNull()) {
            return null;
        } else {
            return convertToEnum(value);
        }
    }

    @Override
    public BasicEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int value = rs.getInt(columnIndex);
        if (rs.wasNull()) {
            return null;
        } else {
            return convertToEnum(value);
        }
    }

    @Override
    public BasicEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        // 数据库中存储int类型
        int value = cs.getInt(columnIndex);
        if (cs.wasNull()) {
            return null;
        } else {
            return convertToEnum(value);
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, BasicEnum param, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, param.getSerial());
    }

    private BasicEnum convertToEnum(int serial) {
        BasicEnum[] iEnums = type.getEnumConstants();
        for (BasicEnum iEnum : iEnums) {
            if (iEnum.getSerial() == serial) {
                return iEnum;
            }
        }
        return null;
    }

}
